package com.budwk.app.sqfw.controllers.admin.customservice;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.budwk.app.exception.ServiceException;
import com.budwk.app.oss.services.SysOssService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.services.common.SqfwCommonForAdminService;
import com.budwk.app.sqfw.services.common.SqfwCustomForAdminCommonService;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfw.vo.SqfwCustomForAdminCommonVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.ResultOfExcelGenerator;
import com.budwk.app.sqfwV2.dto.dto.dayingRoad.DownExcelLedgerReqVo;
import com.budwk.app.sqfwV2.dto.povertyMonitoring.PovertyAlleviationExcelParamForController;
import com.budwk.app.sqfwV2.enums.povertyMonitoring.FormingMaterialEnum;
import com.budwk.app.sqfwV2.service.povertyMonitoring.PovertyAlleviationService;
import com.budwk.app.sqfwV2.service.povertyMonitoring.PovertyMonitoringExcelService;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.starter.common.openapi.annotation.*;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.*;

import java.util.*;

/**
 * @program: dfxy-community-dev
 * @description: 困难人员走访（后台管理系统）
 * @author: LJT
 * @create: 2024-06-29 20:27
 **/
@IocBean
@At("/platform/sqfw/DifficultPerson")
@ApiDefinition(tag = "困难人员走访（后台管理系统）")
@Slf4j
public class DifficultPersonForAdminController {

    @Inject(value = "DifficultPersonForAdminService")
    private SqfwCustomForAdminCommonService sqfwCustomForAdminCommonService;

    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @Inject
    private SqfwCommonForAdminService sqfwCommonForAdminService;

    @Inject
    private PovertyMonitoringExcelService povertyMonitoringExcelService;

    @Inject
    private SysOssService sysOssService;

    /**
     * 列表查询
     */
    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "列表查询")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "create_date", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = SqfwCustomForAdminCommonVO.class
    )
    @ApiResponses(
            implementation = SqfwCustomForAdminCommonVO.class
    )
    @SLog(tag = "公共列表查询（后台管理系统）", value = "${args[0]}}")
    @SaCheckLogin
    public Result<?> list(@Param("..") SqfwCustomForAdminCommonVO bean) {
        Pagination pagination = sqfwCustomForAdminCommonService.list(bean);
        return Result.data(pagination);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @At
    @Ok("json")
    @DELETE
    @ApiOperation(name = "删除列表信息")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SLog(tag = "删除消防信息", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> delete(@Param("id") String id) {
        sqfwCustomForAdminCommonService.delete(id);
        return Result.success();
    }

    @At("/batchDelete")
    @Ok("json")
    @DELETE
    @ApiOperation(name = "批量删除表数据")
    @SLog(tag = "批量删除表数据", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> batchDelete(@Param("ids") List<String> ids) {
        return Result.data(sqfwCommonForAdminService.batchDelete(ids));
    }

    /**
     * 获取下载文件列表及数据检查
     */
    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "获取下载文件列表及数据检查")
    @ApiResponses(
            implementation = SqfwCustomForAdminCommonVO.class
    )
    @SLog(tag = "获取下载文件列表及数据检查", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> checkDataInfoList(@Param("..") SqfwCustomForAdminCommonVO sqfwFormSummaryForAdminVO) {
        return Result.data(sqfwCustomForAdminCommonService.checkDataInfoList(sqfwFormSummaryForAdminVO));
    }

    /**
     * excel下载
     *
     * @param sqfwFormSummaryForAdminVO
     * @return
     */
    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "Excel文件下载")
    @SLog(tag = "Excel文件下载", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> downloadExcel(@Param("excelConfigList") List<ExcelCreateConfig> excelConfigList, @Param("..") SqfwCustomForAdminCommonVO sqfwFormSummaryForAdminVO) {
        return Result.data(sqfwCustomForAdminCommonService.downloadExcel(excelConfigList, sqfwFormSummaryForAdminVO));
    }

    /**
     * pdf下载
     *
     * @param sqfwFormSummaryForAdminVO
     * @return
     */
    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "pdf文件下载")
    @SLog(tag = "pdf文件下载", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> downloadPdf(@Param("excelConfigList") List<ExcelCreateConfig> excelConfigList, @Param("..") SqfwCustomForAdminCommonVO sqfwFormSummaryForAdminVO) {
        return Result.data(sqfwCustomForAdminCommonService.downloadPdf(excelConfigList, sqfwFormSummaryForAdminVO));
    }

    /**
     * 重置(重新生成pdf)
     */
    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "重新生成pdf")
    @ApiResponses(
            implementation = String.class
    )
    @SLog(tag = "重新生成pdf", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> reGeneratePdf(@Param("flowId") String flowId) {
        sqfwCustomForAdminCommonService.reGeneratePdf(flowId);
        return Result.success();
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "获取详情")
    @ApiResponses
    @SLog(tag = "获取详情", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> getHiddenDangerInfo(@Param("hiddenDangerList") List<SqfwCustomForAdminCommonVO> bean, @Param("id") String id) {
        return Result.success();
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "下载excel")
    @ApiFormParams(implementation = DownExcelLedgerReqVo.class)
    @SLog(tag = "下载excel", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> downExcelLedger(@Param("..") DownExcelLedgerReqVo reqVo) {
        List<GenerateExcelUrlVO> generateExcelUrlVOS = new ArrayList<>();
        GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();
        generateExcelUrlVOS.add(generateExcelUrlVO);
        Integer code = Integer.valueOf(reqVo.getFileCode());

        if (reqVo.isDownTemplate()) {
            String filePath = FormingMaterialEnum.getBlankTemplate(code);
            String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
            generateExcelUrlVO.setExcelUrl(sysOssService.upload(CommonFormOfficeUtils.getTempPdfFile(filePath), fileName).getUrl());
        } else {
            if (StringUtils.isBlank(reqVo.getYear())) {
                throw new ServiceException("请选择年度！");
            }
            if (StringUtils.isBlank(reqVo.getQuarter())) {
                throw new ServiceException("请选择季度！");

            }
            PovertyAlleviationExcelParamForController paramForController = new PovertyAlleviationExcelParamForController();
            List<ExcelCreateConfig> excelCreateConfigList = new ArrayList<>();
            ExcelCreateConfig excelCreateConfig = new ExcelCreateConfig();
            if(code==3){
                excelCreateConfig.setReturnWebUrlFlag(false);
            }
            // 页面不送，则默认根据年度、季度计算
            if (StringUtils.isEmpty(reqVo.getFillStartDate())) {
                List<Date> dates = PovertyAlleviationService.getCommunityQuarterTimeRange(Integer.valueOf(reqVo.getYear()), Integer.valueOf(reqVo.getQuarter()));
                reqVo.setFillStartDate(dates.get(0).toString().substring(0, 7));
                reqVo.setFillEndDate(dates.get(1).toString().substring(0, 7));
            }
            excelCreateConfig.setFileIdentity(String.valueOf(code));
            excelCreateConfigList.add(excelCreateConfig);
            paramForController.setExcelCreateConfigList(excelCreateConfigList);
            paramForController.setUserId(SecurityUtil.getUserId());
            paramForController.setCustomerParam(NutMap.NEW()
                    .addv("fillStartDate", reqVo.getFillStartDate())
                    .addv("fillEndDate", reqVo.getFillEndDate())
                    .addv("year", reqVo.getYear())
                    .addv("code", reqVo.getFileCode())
                    .addv("quarter", reqVo.getQuarter())
                    .addv("houseHoldNumber",reqVo.getHouseNumber()));
            paramForController.setYear(reqVo.getYear());
            paramForController.setQuarter(reqVo.getQuarter());
            paramForController.setStartDate(DateUtil.parse(reqVo.getFillStartDate(), "yyyy-MM"));
            paramForController.setWebSig(true);
            List<ResultOfExcelGenerator> excel = povertyMonitoringExcelService.createExcel(paramForController);
            if (CollectionUtil.isNotEmpty(excel)) {
                generateExcelUrlVO.setExcelUrl(excel.get(0).getExcelUrl());
            }
        }
        return Result.data(generateExcelUrlVOS);
    }
}
